package sdfi.lee.Question;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.MapMessage;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.struts2.ServletActionContext;

import sdfi.lee.DAO.QuestionDAO;
import sdfi.lee.JMS.ConnectionFactory;
import sdfi.lee.Logger.MyLogger;
import sdfi.lee.Properties.ReaderProperties;

import com.opensymphony.xwork2.ActionContext;
public class Question implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String question;
	private String answerqueue;
	private List<Answer> listAnswer;
	private List<String> list=new ArrayList<String>();
	private Connection con=null;
	public List<Answer> getListAnswer() {
		return listAnswer;
	}

	public void setListAnswer(List<Answer> listAnswer) {
		this.listAnswer = listAnswer;
	}
	public void addAnswerToList(Answer answer)
	{
		if(this.listAnswer==null) this.listAnswer=new ArrayList<Answer>();
		this.listAnswer.add(answer);
	}
	
	public String getQuestion() {
		return question;
	}

	public void setQuestion(String question) {
		this.question = question;
	}

	
	public Question(){
		
	}
	
	public String getAnswerqueue() {
		return answerqueue;
	}
	public void setAnswerqueue(String answerqueue) {
		this.answerqueue = answerqueue;
	}
	
	
	
	
	public String execute()
	{
		boolean isget=false;
		try
		{
		Object obj=ActionContext.getContext().getSession().get("anqueue");
		if(obj==null)
		{
			this.setAnswerqueue("q-"+ServletActionContext.getRequest().getSession().getId().substring(0, 9));
			ActionContext.getContext().getSession().put("anqueue", this.getAnswerqueue());
		}
		else this.setAnswerqueue(obj.toString());
		isget=this.get();
		if(isget)
	
			return "success";
		else
			
			return "error";
	
		}catch(Exception ee)
		{
			MyLogger.Logger(ee.getMessage(), null, "info");
			return "error";
		}
		finally
		{
			if(isget)
			{
				new QuestionDAO().addQuestionToDB(list, question);
				
			}
		}
		
			
	}
	private boolean get()
	{	
		boolean is =false;
		con=ConnectionFactory.getCon();
		try
		{
			if(null==con) 
			{
				
					ReaderProperties rp=new ReaderProperties();
					String port=rp.getProperty("mq-port");
					String path=rp.getProperty("mq-path");
					String url="tcp://localhost:61616";
					if(path!=null&&port!=null&&!"".equals(path)&&!"".equals(port))
						url=path+":"+port;

			    	ActiveMQConnectionFactory at=new ActiveMQConnectionFactory(url);
				
				con=at.createConnection();
				}
		
			con.start();
			Session session=con.createSession(false, Session.AUTO_ACKNOWLEDGE);
			String queue="qa";
			MessageProducer producer=session.createProducer(session.createQueue(queue));
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
			String flag=(""+Math.random()).replace(".", "1");
			MessageConsumer consumer=session.createConsumer(session.createQueue(this.getAnswerqueue()));
			MyLogger.Logger("user ask a question send over",null, "info");
			MapMessage map=session.createMapMessage();
			map.setString(answerqueue,flag+"#"+this.question);
			MapMessage mapmsg=null;	
			producer.send(map);		
			boolean isAnswer=false;
			while(!isAnswer)
			{
				mapmsg=(MapMessage)consumer.receive(30000);
				if(mapmsg!=null)
					{
						Enumeration enumr= mapmsg.getMapNames();
						while(enumr.hasMoreElements())
						{
						
							Object obj=enumr.nextElement();
							String key=obj.toString();
							if(!flag.equals(key)&&!key.contains(flag)){
								is=false;
								break;
							}
							if(flag.equals(key))
								{
									this.question=mapmsg.getString(key);
								}
							else
							{
							String an=mapmsg.getString(key).toString();
							Answer answer=new Answer();
							answer.setFile(an.substring(0,an.indexOf("#")));
							answer.setAnswer(an.substring(an.indexOf("#")+1));
							list.add(an.substring(an.indexOf("#")+1));
							this.addAnswerToList(answer);
							}
							is=true;
						}
						if(is=true)
						MyLogger.Logger("response over", null, "info");
						isAnswer=true;//找到答案
					}
					else
					{
						Answer answer=new Answer();
						answer.setAnswer("暂无答案！！！");
						this.addAnswerToList(answer);
						is=false;
						isAnswer=true;//接收超时
					}
			}
			session.close();
			con.stop();
			return is;
		}
		catch(Exception ee)
		{
			MyLogger.Logger(ee.getMessage(), null, "error");
			ee.printStackTrace();
			return false;
		}
	}
	

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		Answer answer=null;
		for(int i=0;i<list.size();i+=2)
		{
			
			answer=new Answer();
			answer.setAnswer(list.get(i));
			if((i+1)<list.size())
			answer.setFile(list.get(i+1));
		
			this.addAnswerToList(answer);
		}
		this.list = list;
	}


	
}
